var prefix = ctx +"module/terminal/record/info"
$(function() {
    load();
});
function load(){
    layui.use(['element','form','table'], function() {
        var form = layui.form ,
            $ = layui.jquery,
            table = layui.table,
            element = layui.element;//载入table模块
        //触发事件
        var active = {
            tabAdd: function(tabAdd){
                console.log('tabAdd',tabAdd)
                //新增一个Tab项
                element.tabAdd('demo', {
                    title: '新选项'+ (Math.random()*1000|0) //用于演示
                    ,content: '内容'+ (Math.random()*1000|0)
                    ,id: new Date().getTime() //实际使用一般是规定好的id，这里以时间戳模拟下
                })
            }
            ,tabDelete: function(othis){
                console.log('othis',othis)
                //删除指定Tab项
                element.tabDelete('demo', '44'); //删除：“商品管理”
                othis.addClass('layui-btn-disabled');
            }
            ,tabChange: function(res){
                console.log('tabChange',res)
                //切换到指定Tab项
                element.tabChange('demo', '22'); //切换到：用户管理
            }
        };
        //Hash地址的定位
        var layid = location.hash.replace(/^#test=/, '');

        element.tabChange('test', layid);
        element.on('tab(test)', function(elem){
            console.log('elem',elem)
            console.log('$(this).attr(\'lay-id\')',$(this).attr('lay-id'))
            location.hash = 'test='+ $(this).attr('lay-id');

            var searchParams = {};
            searchParams['search_eq_shopId']=$('#shopId').val();
            searchParams['search_eq_terminalNum']=$('#terminalNum').val();

            console.log('terminalNum',$('#terminalNum').val());


            if($('#begin_date').val()!="" && $('#end_date').val()!=""){
                searchParams['search_ge_createTime']=$('#begin_date').val() + " 00:00:00";
                searchParams['search_le_createTime']=$('#end_date').val()+ " 23:59:59";
            }
            var tab_id = $(this).attr('lay-id')
            searchParams['tab_id']=tab_id;
            $("#tab_id").val(tab_id)
            console.log('tab_id',tab_id)

            // table.reload('currentTableId', {
            //     page: {curr: 1}
            //     , where: {
            //         searchParams: searchParams,
            //         sorts:{"state":"desc"}
            //     }
            // }, 'data');
            reloadTable(table,'currentTableId1',searchParams)
        });

        initTable(table,form,'#exampleTable1','currentTableId1',1)
        initTable(table,form,'#exampleTable2','currentTableId2',2)
        initTable(table,form,'#exampleTable3','currentTableId3',3)
        initTable(table,form,'#exampleTable4','currentTableId4',4)
    });
}

//表格重载方法
function reloadTable(table,id,param){
    table.reload(id, {
        page: {curr: 1}
        , where: {
            searchParams: param,
            sorts:{"state":"desc"}
        }
    }, 'data');
}

function initTable(table,form,exampleTable,id,type){
    var checkedArr=[];
    var searchParams = {};
    searchParams['search_eq_shopId']=$('#shopId').val();
    searchParams['search_eq_terminalNum']=$('#terminalNum').val();
    searchParams['tab_id']=type;

    if($('#begin_date').val()!="" && $('#end_date').val()!=""){
        searchParams['search_ge_createTime']=$('#begin_date').val() + " 00:00:00";
        searchParams['search_le_createTime']=$('#end_date').val()+ " 23:59:59";
    }
    $(".layui-table-cell .imgurl").unbind("click");
    console.log('type',type)
    var cols;
    if(type == 1 || type == 2){
        cols = [[
            { type : 'checkbox',fixed : 'left' },
            { field : 'shopName',  title : '企业名称',  align : 'center', },
            { field : 'terminalName',  title : '设备名称', align : 'center',   },
            { field : 'terminalNum',  title : '设备编号', align : 'center',   },
            { field : 'userName',  title : type == 1 ? '巡检人':'清理人', align : 'center',   },
            { field : 'createTime',  title : type == 1 ? '巡检时间':'清理时间', align : 'center',   },
            { field : 'checkResult',  title : type == 1 ? '巡检说明': '清理说明', align : 'center',   },
            { title : '相关图片', align : 'center',
                templet: function (item) {
                    var imgs = "";
                    if(item.imgsList!=undefined){
                        if(item.imgsList.length > 0){
                            for(var index in item.imgsList){
                                imgs += "<img src='"+item.imgsList[index]+"' class='imgurl_"+type+"' style='margin-left: 5px;' width='50' height='50' />";
                            }
                        }
                    }
                    return imgs;
                },
            },
            { title : '状态', align : 'center',
                templet: function (item) {
                    var css = loadDictCssStyle('check-state')[item.checkState]
                    return '<span class="'+css+'">' + (loadCategory('check-state')[item.checkState] ? loadCategory('check-state')[item.checkState] : '') + '</span>';
                },
            },
            { title: '操作', templet: '#currentTableBar', align: "center"}
        ]];
    } else if(type == 3){
        cols = [[
            { type : 'checkbox',fixed : 'left' },
            { field : 'shopName',  title : '所属企业', align : 'center', width:200  },
            { field : 'terminalNum',  title : '设备编号', align : 'center',   },
            { field : 'terminalName',  title : '设备名称', align : 'center',   },
            { title : '二维码', align : 'center',
                templet: function (item) {
                    return "<a href=\"javascript:void(0);\" imgurl=\""+item.qrcodeImg+"\" class=\"grid-column-qrcode text-muted\">" +
                        "           <i class=\"fa fa-qrcode\"></i>" +
                        "       </a>"+
                        "&nbsp;&nbsp;<a href='"+prefix + "/download/"+item.terminalNum+"' download='terminal_qr_"+item.terminalNum+".jpg'><i class=\"fa fa-download\"></i>No."+item.terminalNum+"</a>";
                },
            },
            { field : 'deviceFittingName',  title : '保养点', align : 'center',   },
            { field : 'healthRunhuaji',  title : '使用润滑剂', align : 'center',   },
            { title : '保养周期', align : 'center',
                templet: function (item) {
                    return '1次/' + item.healthCount + (loadCategory('clean-cycle-type')[item.healthCountUnit] ? loadCategory('clean-cycle-type')[item.healthCountUnit] : '');
                },
            },
            { title : '保养状态', align : 'center',
                templet: function (item) {
                    if(item.currentHealthCount > 0){
                        return '<span class="label label-success">当前周期已保养</span>';
                    }else{
                        return '<span class="label label-danger">当前周期未保养</span>';
                    }
                },
            },
            { field : 'lastHealthTime',  title :'最后保养时间', align : 'center',   },
            { title: '操作', minWidth:180,  templet: '#currentTableBar',fixed: "right", align: "center"}
        ]];
    }else  if(type == 4){
        cols = [[
            { field : 'shopName',  title : '企业名称',  align : 'center', },
            { field : 'terminalName',  title : '设备名称', align : 'center',   },
            { field : 'terminalNum',  title : '设备编号', align : 'center',   },
            { field : 'repairName',  title : '处理人员', align : 'center',   },
            { field : 'createTime',  title : '上报时间', align : 'center',   },
            { field : 'repairTime',  title : '处理时间', align : 'center',   },
            { title : '处理状态', align : 'center',
                templet: function (item) {
                    if(item.repairState == 0){
                        return "<span class=\"label label-danger\">未处理</span>";
                    }else{
                        return "<span class=\"label label-primary\">已处理</span>";
                    }
                },
            },
            { title: '操作', width: "20%", templet: '#currentTableBar', align: "center"}
        ]];
    }
    console.log('cols',cols)
    //初始化table
    table.render({
        elem: exampleTable,//承载数据的table Id
        url: prefix + "/list",//请求数据连接
        toolbar: '#toolbarDemo',
        cellMinWidth: 80,//全局定义所有常规单元格的最小宽度（默认：60）
        even: true,//是否开启隔行变色
        loading:true,//是否显示加载条
        where :{
            searchParams:searchParams,
            sorts:{"state":"desc"}
        },
        // page: true,//是否分页
        page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
            layout: [ 'prev', 'page', 'next', 'skip', 'count','limit'] //自定义分页布局
        },
        cols: cols,
        id: id,//表格Id  'currentTableId'
        done: function(res, curr, count){
            $(".grid-column-qrcode").each(function() {
                $(this).click(function() {
                    previewImg(this);
                })
            });
            $(".layui-table-cell .imgurl_" + type).each(function() {
                $(this).click(function() {
                    previewImg(this);
                })
            });
        } //解决最右侧列不能固定的问题
    });

    /**
     * 操作栏tool  监听事件
     */
    table.on('tool(currentTableFilter)', function (obj) {
        if (obj.event === 'edit') {  // 监听添加操作
            console.log('obj',obj.data.id)
            edit(obj.data.id);
        } else if (obj.event === 'delete') {  // 监听删除操作
            console.log('obj',obj.data.id)
            remove(obj.data.id);
        }else if (obj.event === 'record') {  // 监听删除操作
            goRecordList(obj.data.id);
        } else if (obj.event === 'qrcode') {  // 监听删除操作
            resetQrcode(obj.data.id);
        } else if (obj.event === 'fitting') {  // 监听删除操作
            goFitting(obj.data.id);
        }
        else if (obj.event === 'xunjian') {  // 监听删除操作
            goFitting(obj.data.id);
        }
        else if (obj.event === 'clean') {  // 监听删除操作
            goFitting(obj.data.id);
        }
        else if (obj.event === 'baoyang') {  // 监听删除操作
            goFitting(obj.data.id);
        }
        else if (obj.event === 'repair') {  // 监听删除操作
            goFitting(obj.data.id);
        }
    });
    // 监听搜索操作
    form.on('submit(data-search-btn)', function (data) {
        //执行搜索重载
        // reLoad();
        reloadTable(table,'currentTableId' + type,searchParams)
        return false;
    });
    /**
     * 操作栏tool  监听事件
     */
    table.on('toolbar(currentTableFilter)', function (obj) {
        if (obj.event === 'add') {  // 监听添加操作
            add();
        } else if (obj.event === 'back') {  // 监听添加操作
            goBack();
        }else if (obj.event === 'upload') {  // 批量上传设备
            batchAdd();
        } else if(obj.event === 'batchRemove'){
            var checkStatus = table.checkStatus('currentTableId'),data = checkStatus.data;
            checkedArr = data;
            var ids = [];
            for(var index in checkedArr){
                ids.push(checkedArr[index].id);
            }
            if (ids.length < 1) {
                layer.msg('无选中项');
                return false;
            }
            batchRemove(ids);
        } else if(obj.event === 'batchQrcode'){
            var checkStatus = table.checkStatus('currentTableId'),data = checkStatus.data;
            checkedArr = data;
            var ids = [];
            for(var index in checkedArr){
                ids.push(checkedArr[index].id);
            }
            if (ids.length < 1) {
                layer.msg('无选中项');
                return false;
            }
            batchQrcode(ids);
        }
    });
    table.on('checkbox(currentTableFilter)', function(obj){
        var checkStatus = table.checkStatus('currentTableId'),data = checkStatus.data;
        console.log('checkStatus',checkStatus);
        console.log('data',data);
        checkedArr = data;
    });
}

$('#add_sends').click(function () {
    var checkStatus = table.checkStatus('te');
    var ids = [];
    $(checkStatus.data).each(function (i, o) {//o即为表格中一行的数据
        ids.push(o.student_id);
    });
    if (ids.length < 1) {
        layer.msg('无选中项');
        return false;
    }
    ids = ids.join(",");
    layer.confirm('您确定要分发该课程吗？', function (index) {
        $.get("{:url('add_sends')}", {ids: ids, courseId: "{$courseId}"}, function (res) {
            if (res.code == 1) {
                layer.msg(res.msg, {time: 1000, icon: 1});
                tableIn.reload();
            } else {
                layer.msg(res.msg, {time: 1000, icon: 2});
            }
        });
        layer.close(index);
    });
});


function goBack(){
    window.location.href= ctx + "module/shop";
}

function goXunJianRecord(id) {
    var index = layer.open({
        type : 2,
        title : '编辑',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '800px', '550px' ],
        content : prefix + '/edit/' + id // iframe的url
    });
    layer.full(index);
}

function goCleanRecord(id) {
    var index = layer.open({
        type : 2,
        title : '编辑',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '800px', '550px' ],
        content : prefix + '/edit/' + id // iframe的url
    });
    layer.full(index);
}

function resetQrcode(id){
    $.ajax({
        url : prefix + "/resetQrcode",
        type : "post",
        data : {
            'id' : id
        },
        success : function(r) {
            if (r.code==0) {
                layer.msg(r.msg);
                reLoad();
            }else{
                layer.msg(r.msg);
            }
        }
    });
}

function reLoad() {
    var searchParams = {};
    searchParams['search_eq_shopId']=$('#shopId').val();
    searchParams['search_eq_terminalNum']=$('#terminalNum').val();
    layui.use(['table'], function() {
        var table = layui.table;//载入table模块
        table.reload('currentTableId', {
            page: {curr: 1}
            , where: {
                searchParams: searchParams,
                sorts:{"state":"desc"}
            }
        }, 'data');
    });
}


function previewImg(obj) {
    var img = new Image();
    img.src = obj.src;
    var imgHtml = "<img src='" + obj.src + "' width='600' height='500'/>";
    //弹出层
    layer.open({
        type: 1,
        // shade: true,
        shadeClose : true, // 点击遮罩关闭层
        title: false, //不显示标题
        area:[ '600px', '500px' ],
        content: imgHtml, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
        cancel: function () {

        }
    });
}

function add() {
    var isclean = $('#isClean').val()
    var index = layer.open({
        type : 2,
        title : '增加',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '800px', '550px' ],
        content : prefix + '/add/' + isclean// iframe的url
    });
    // layer.full(index);
}

function goRecordList(id) {
    window.location.href = prefix + '/record/terminal/'+id;
}

function goFitting(id) {
    window.location.href =  prefix + '/fitting/' + id;
}

function edit(id) {
    var index = layer.open({
        type : 2,
        title : '编辑',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '800px', '550px' ],
        content : prefix + '/edit/' + id // iframe的url
    });
    // layer.full(index);
}

function remove(id) {
    layer.confirm('确定要删除选中的记录？', {
        btn : [ '确定', '取消' ]
    }, function() {
        $.ajax({
            url : prefix+"/remove",
            type : "post",
            data : {
                'id' : id
            },
            success : function(r) {
                if (r.code==0) {
                    layer.msg(r.msg);
                    reLoad();
                }else{
                    layer.msg(r.msg);
                }
            }
        });
    })
}

function batchRemove(ids) {
    layer.confirm("确认要删除选中的'" + ids.length + "'条数据吗?", {
        btn : [ '确定', '取消' ]
        // 按钮
    }, function() {
        $.ajax({
            type : 'POST',
            data : {
                "ids" : ids
            },
            url : prefix + '/batchRemove',
            success : function(r) {
                if (r.code == 0) {
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    }, function() {});
}


function batchQrcode(ids) {
    $.ajax({
        type : 'POST',
        data : {
            "ids" : ids
        },
        url : prefix + '/batchQrcode',
        success : function(r) {
            if (r.code == 0) {
                layer.msg(r.msg);
                reLoad();
            } else {
                layer.msg(r.msg);
            }
        }
    });
}

function batchAdd() {
    var index = layer.open({
        type : 2,
        title : '批量增加',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '800px', '320px' ],
        content : ctx + 'module/terminal/goBatchAdd' // iframe的url
    });
}
